from random import randint
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from . import constants
from django.http import HttpResponse
from rest_framework.generics import GenericAPIView
from .serializers import RegisterSMSCodeSerializer
from libs.yuntongxun.sms import CCP

# Create your views here.

#  图片验证码
class RegisterImageCodeView(APIView):

    # GET# verifications / imagecodes / (?P < image_code_id >.+) /
    # 需要链接redis数据库 获取uudi 和图片验证码 和前端输出的进行对比

    def get(self,request,image_code_id):

        text,image = captcha.generate_captcha()

        redis_conn = get_redis_connection('code')

        redis_conn.setex('img_%s'%image_code_id,constants.IMAGE_CODE_EXPIRE_TIME,text)

        print(image_code_id)

        return HttpResponse(image,content_type='image/jpeg')


# 短信验证码
class RegisterSMSCodeView(GenericAPIView):
    '''
    访问方式： GET /verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx & image_code_id=xxxx
    '''

    serializer_class = RegisterSMSCodeSerializer

    def get(self,request,mobile):

        serializer = self.get_serializer(data=request.query_params)

        serializer.is_valid(raise_exception=True)

        redis_conn = get_redis_connection('code')
        #
        if redis_conn.get('sms_flag_%s'%mobile):
            return Response(status=status.HTTP_429_TOO_MANY_REQUESTS)

        sms_code = '%06d'%randint(1,999999)

        # redis_conn.setex('sms_%s'%mobile,constants.SMS_CODE_EXIPRE_TIME,sms_code)
        #
        # redis_conn.setex('sms_flag_%s'%mobile,60,1)
        pl = redis_conn.pipeline()

        pl.setex('sms_%s'%mobile,constants.SMS_CODE_EXIPRE_TIME,sms_code)
        pl.setex('sms_flag_%s'%mobile,60,1)

        pl.execute()

        # ccp = CCP()
        # ccp.send_template_sms(mobile,[sms_code,5],1)

        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile,sms_code)


        # celery -A celery_tasks.main worker -l info

        print(sms_code)
        return Response({
            'message':'ok'
        })



